package com.gmail.hy87cn.hellohi.server;

import java.util.ArrayList;

import com.gmail.hy87cn.hellohi.shared.ERoomState;

/**
 * @author HeYi
 * 
 */
public class HiUserManager {
	private ArrayList<HiUserPackage> userList = new ArrayList<HiUserPackage>();
	private HiRoomPackage waitingRoom = new HiRoomPackage();
	private static HiUserManager sInstance;

	public static HiUserManager sGetInstance() {
		if (sInstance == null) {
			sInstance = new HiUserManager();
		}
		return sInstance;
	}

	private HiUserManager() {
	}

	public int createUser() {
		HiUserPackage user = null;
		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i) == null) {
				user = new HiUserPackage(i);
				userList.set(i, user);
				return user.getUser().getId();
			}
		}
		user = new HiUserPackage(userList.size());
		userList.add(user);
		return user.getUser().getId();
	}

	public HiUserPackage getUser(int id) {
		return userList.get(id);
	}

	public void removeUser(int id) {
		userList.set(id, null);
	}

	public void connect(int id, String facebookId) {
		HiUserPackage user = userList.get(id);
		if (user.getRoomPackage() == null) {
			if (waitingRoom.getRoom().getState() != ERoomState.Open) {
				waitingRoom = new HiRoomPackage();
			}
			user.getUser().setFacebookId(facebookId);
			user.setRoomPackage(waitingRoom);
			waitingRoom.addUser(user);
		}
	}

	public void disconnect(int id) {
		HiUserPackage user = userList.get(id);
		HiRoomPackage room = user.getRoomPackage();
		if (room != null) {
			user.setRoomPackage(null);
			room.removeUser(user);
		}
	}
}
